import { JSEncrypt } from '@/utils/jsencrypt/lib/JSEncrypt'

const CookiePrivateKey = 'MICRO-WEB:private-key'

function setPrivateKey(privateKey) {
  return localStorage.setItem(CookiePrivateKey, privateKey);
  // return Cookies.set(CookiePrivateKey, privateKey)
}

const rsaPrivate = new JSEncrypt()

export function refreshRsa() {
  removeRsaValue()
  initRsa()
}

export function initRsa() {
  var privateKey = localStorage.getItem(CookiePrivateKey)
  // var privateKey = Cookies.get(CookiePrivateKey)
  if (privateKey && privateKey != 'null') {
    rsaPrivate.setKey(privateKey)
  } else {
    privateKey = rsaPrivate.getPrivateKey()
  }
  setPrivateKey(privateKey)
}

const rsaPublic = new JSEncrypt()
var publicKey = process.env.VUE_APP_PUBLIC_KEY
rsaPublic.setPublicKey(`-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`)

export function removeRsaValue() {
  return localStorage.setItem(CookiePrivateKey, null);
}

export function encrypt(json) {
  return rsaPublic.encryptLong(json)
}

export function decrypt(json) {
  return rsaPrivate.decryptLong(json)
}

export function getClientPublicKey() {
  return rsaPrivate.getPublicKey().replace(`-----BEGIN PUBLIC KEY-----\n`, ``).replace(`\n-----END PUBLIC KEY-----`, ``)
}
